//
//  OAuthViewController.swift
//  Swift微博
//
//  Created by 陈竹 on 16/2/24.
//  Copyright © 2016年 陈竹. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    private let webView=UIWebView()
    override func loadView() {
        self.view=webView
        title="登陆新浪微博"
        self.view.backgroundColor=UIColor.redColor()
        //左边按钮
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "取消", style: .Done, target: self, action: "didClickcloseBtn")
        //右边按钮
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .Done, target: self, action: "didClickRightBtn")
        
    }
    @objc private func didClickcloseBtn(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func didClickRightBtn(){
        
        //填充帐号密码的js
        let js = "document.getElementById('userId').value='15307134911';" +
        "document.getElementById('passwd').value='chenzhu89530636';"
        
        // 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //手写界面的时候必须设置背景颜色
        view.backgroundColor=UIColor.whiteColor()
        //跳转请求登陆界面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
        webView.delegate=self
    }
}
extension OAuthViewController:UIWebViewDelegate{
    ///  将要开始加载页面
    ///
    ///  - parameter webView:        webView
    ///  - parameter request:        request
    ///  - parameter navigationType: 导航类型
    ///
    ///  - returns: 是否加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果url中不是回调地址，继续加载
        if let urlString=request.URL?.absoluteString where
            !urlString.hasPrefix(NetworkTools.sharedTools.AppRedirectUri) {
                return true
        }
        //如果回调地址不包含code请求码说明取消授权
        guard let query=request.URL?.query where query.hasPrefix("code=")else{
            print("取消授权")
            dismissViewControllerAnimated(true, completion: nil)
            return false
        }
        
        print("请求字符串:\(query)")
        let code=query.substringFromIndex("code=".endIndex)
        print("请求码:\(code)")
        NetworkTools.sharedTools.loadAccessToken(code) { (result) -> () in
            
            guard let result = result else{
                print("网络不给力")
                return
            }
            //设置用户单例的数据
            UserAccount.sharedUserAccount.updateUserAccount(result)
            //创建登陆成功通知
            NSNotificationCenter.defaultCenter().postNotificationName(CZWeiBoLoginSuccessedNotification, object: nil)
            self.didClickcloseBtn()
        }

        return false
        
        
    }
    
}
